<template>
  <div style="background-color: #ebeef5">
    <el-row type="flex" class="row-bg">
      <el-col :span="6" class="left_m" style="background-color: white; font-size: 16px; overflow: auto;">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick"
          style="margin: 0 8px 0 0;background-color: white;min-height: 50%">
          <el-tab-pane label="文件目录" name="first">
            <div style="height:calc(80vh - 50px);overflow:auto;">
              <el-tree :data="treedata" :props="props" :load="loadNode" lazy
                v-model="checkedNodes"
                @node-click="handleNodeClick" />
            </div>

            <div style="
                width: 97.6%;
                height: 50px;
                background-color: white;
                border-top: solid 1px #e8eaec;
              ">
              <el-checkbox v-model="IsChecked" style="float:left; margin: 5px 10px 0 20px">包含下级</el-checkbox>
            </div>
          </el-tab-pane>
          <el-tab-pane label="汇总查询" name="second">
            <el-form :model="queryForm" label-width="120px" class="demo-ruleForm">
              <el-form-item label="所属目录：">
                <div @click="openDrawer" style="display: inline-block;">
                  <el-input v-model="queryForm.diretoryName"
                  placeholder="单击此处选择发布目录"
                  readonly style="width: 200px;" />
                </div>
                <el-checkbox v-model="includesCheck" style="margin-right:15px;">包含下级</el-checkbox>
              </el-form-item>
              <el-form-item label="保密级别：">
                <el-select v-model="queryForm.secrecyLevel" style="width: 78%; font-size: 16px" size="mini">
                  <el-option label="公开" value="公开" />
                  <el-option label="内部" value="内部" />
                  <el-option label="秘密" value="秘密" />
                  <el-option label="机密" value="机密" />
                </el-select>
              </el-form-item>
              <el-form-item label="搜索关键词：">
                <el-input size="mini" style="width: 78%; font-size: 16px" placeholder="请输入" v-model="queryForm.fileTitle"
                  readonlyd />
              </el-form-item>
              <el-form-item label="搜索全文：">
                <el-input size="mini" style="width: 78%; font-size: 16px" placeholder="请输入"
                  v-model="queryForm.fileContent" readonlyd />
              </el-form-item>
              <el-form-item label="热门标签：" style="height:200px;overflow:auto">
                <el-tag v-for="(item, index) in items" size="small" style="font-size: 16px;cursor:pointer"
                  @click="changeColor(index)" :key="index" :effect="item.tagEffect">
                  {{ item.label }}
                </el-tag>
              </el-form-item>
              <el-form-item label="文号：">
                <el-input size="mini" style="width: 78%; font-size: 16px" placeholder="请输入" v-model="queryForm.fileNumber"
                  readonlyd />
              </el-form-item>
              <el-form-item label="发文单位：">
                <el-input size="mini" style="width: 78%; font-size: 16px" placeholder="请输入"
                  v-model="queryForm.fileReleaseUnitName" readonlyd />
              </el-form-item>
              <el-form-item label="文件发文日期：">
                <el-date-picker v-model="fileReleaseUnitDate" style="width: 78%; font-size: 16px" type="daterange"
                  range-separator="-" size="small" value-format="yyyy-MM-dd" start-placeholder="开始日期"
                  end-placeholder="结束日期" @change="dataPickerChange" />
              </el-form-item>
            </el-form>

            <div class="search_b">
              <el-button type="primary" plain size="mini" icon="el-icon-search" @click="handleTableSearch">
                查询
              </el-button>
              <el-button type="" plain size="mini" icon="el-icon-search" @click="reset()">
                重置
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <el-col :span="18" style="margin-left: 10px">
        <div class="">
          <!--table-->
          <div class="doc-l" :style="heightY2">
            <div class="doc-i" v-for="(item, index) in fileTableData" :key="index">
              <div class="doc-it">
                <p class="doc-it-tit">
                  {{ item.fileTitle }}
                </p>
                <span class="doc-it-tab">
                  <span>{{
                    item.fileOrder == null ? "暂无" : item.fileOrder
                  }}</span>
                  <span>{{ item.fileTitle }}</span>
                  <span>{{ item.fileReleaseUnitName }}</span>
                  <span>{{ item.fileNumber }}</span>
                  <span>{{
                    item.fileReleaseUnitDate
                    ? item.fileReleaseUnitDate.substring(0, 10)
                    : ""
                  }}</span>
                </span>
                <div class="doc-it-bth">
                  <el-button type="warning" plain size="mini" icon="el-icon-search" @click="docPrew(item)">
                    预览
                  </el-button>
                  <el-button type="primary" plain size="mini" icon="el-icon-download" @click="docDown(item)">
                    下载
                  </el-button>
                  <el-button type="" plain size="mini" icon="el-icon-search" @click="docText(item.fileId)">
                    文本
                  </el-button>
                </div>
              </div>
              <div class="doc-ib">
                <p>{{ item.fileContent }}</p>
                <p style="margin-top: 5px">
                  关键词>> <span>{{ item.fileLabel }}</span>
                </p>
              </div>
            </div>
            <div class="search-empty-list" v-if="fileTableData.length <= 0">暂无数据</div>
          </div>
          <!-- 循环渲染数据-->
          <div style="
              width: 100%;
              float: left;
              text-align: center;">
            <vxe-pager background align="left" @page-change="handleCurrentChange"
              :current-page.sync="page.currentPage"
              :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'JumpNumber',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total',
              ]" />
          </div>
        </div>
      </el-col>
    </el-row>
    <docPreviewPage ref="docPreviewPage" />
    <docShowTextPage ref="docShowTextPage" />
    <DiretorySelect ref="diretorySelect" @onChange="handleDiretorySelect" />
  </div>
</template>
<script>
import { fileBaseList } from "@/api/knowledge/fileBase";
import { getTreeDataList } from "@/api/knowledge/diretory";
import { getList } from "@/api/knowledge/label";
import { DOWN_FILES } from "@/api/office/file";
import docPreviewPage from "./docPreviewPage";
import docShowTextPage from "./docShowTextPage";
import store from "@/store";
import webapp from "@/config/webapp";

import DiretorySelect from '../components/diretorySelect.vue'

export default {
  name: `docSearchIndex`,
  components: { docPreviewPage, docShowTextPage, DiretorySelect },
  data() {
    return {
      treedata: [],
      props: {
        label: `name`,
        children: `children`, // 显示子节点的字段名
        isLeaf: (node) => !node.isParent && !node.children,
      },
      checkable: true, // 是否显示复选框
      checkedNodes: [],
      heightY: { height: `${window.innerHeight - 120}px` },
      heightY2: { height: `${window.innerHeight - 173}px` },
      items: [],
      options: [],
      // 请求参数
      queryForm: {
        fileContent: ``, //全文
        secrecyLevel: ``,//点击的多个关键字
        fileTitle: ``, //文档标题
        fileNumber: ``, //文号
        fileReleaseUnitName: ``, //发文单位
        releaseTimeStart: ``,
        releaseTimeEnd: ``,
      },
      page: {
        currentPage: 1,
        pageSize: 20,
        totalResult: 0,
      },
      fileReleaseUnitDate: ``,
      fileTableData: [],
      loadingShowTable: false,
      loadingTable: false,
      activeName: `first`, //tab切换
      treedataId: `0001`,
      searchkeys: [],
      isLeaf: ``,
      IsChecked: false,
      fileBussinessTypeCode: "111",
      fileBusinessTypeId: "111",
      includesCheck: false,
    };
  },
  watch: {
    "queryForm.searchType": {
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.queryForm.currentPage = 1;
        }
      },
      deep: true,
    },
  },
  async created() {
    this.init();
    this.getTreeData();
    this.getFileDataList();
    await this.getTagDataList();
  },
  methods: {
    init() {
      this.dialogVisible = true;
    },

    // 樹的選擇
    handleDiretorySelect(data) {
      this.$set(this.queryForm, 'diretoryName', data.name);
      this.queryForm.diretoryId = data.id;
    },

    handleTableSearch() {
      this.getFileDataList(this.queryForm.diretoryId)
    },
    getFileDataList(fdId) { //数据渲染
      let isContainsOrgChild = '1'
      if (this.IsChecked == false && this.includesCheck == false) {
        isContainsOrgChild = '0'
      }
      const params = {
        data: {
          pageSize: this.page.pageSize,
          currentPage: this.page.currentPage,
          fileDiretoryId: fdId ? fdId : this.treedataId,
          fileTitle: this.queryForm.fileTitle, //文档标题
          fileContent: this.queryForm.fileContent, //搜索全文
          fileSecrecyLevel: this.queryForm.secrecyLevel, //保密级别
          fileIsPublic: 1, //是否发布,因为只展示发布的数据
          fileNumber: this.queryForm.fileNumber, //文号
          fileReleaseUnitName: this.queryForm.fileReleaseUnitName, //发文单位
          isContensDown: isContainsOrgChild,
        },
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
      };

      if (this.searchkeys.length) {
        params.data.fileLabel = this.searchkeys.join(`,`);//新增参数：文件标签
      }

      // 添加额外的判断条件，只有当日期不为空时才会将日期加入搜索条件中
      if (this.queryForm.releaseTimeStart || this.queryForm.releaseTimeEnd) {
          params.data.fileReleaseUnitDateStart = this.queryForm.releaseTimeStart,
          params.data.fileReleaseUnitDateEnd = this.queryForm.releaseTimeEnd
      }
      fileBaseList(params).then((data) => {
        if (data.result) {
          this.fileTableData = data.resultdata.data;
          this.page.totalResult = data.resultdata.count;
        }
      });
    },
    getTreeData() {
      const params = {
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
        data: {
          fileBussinessTypeCode: this.fileBussinessTypeCode,
          fileDiretoryId: null,
        },
      };
      getTreeDataList(params).then((data) => {
        if (data.result === true) {
          this.treedata = data.resultdata.data;
          const [treeItem] = this.treedata
          this.treedataId = treeItem.id;
          console.log(this.treedataId, "id");
          const items = [];
          data.resultdata.data.forEach(function (obj) {
            items.push({
              label: obj.name,
              id: obj.id,
            });
          });
          this.options = items;
        }
        else {
          this.$message({
            type: `warning`,
            message: `获取信息出错`,
          });
        }
      });
    },
    // tree的懒加载数据
    loadNode(node, resolve) {
      this.isLeaf = node.isLeaf;
      if (node.level === 0) {
        return resolve(this.treedata);
      }
      if (node.level > 9999) return resolve([]);
      // 请求子节点数据
      setTimeout(() => {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          data: {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryId: node.data.id,
          },
        };

        this.curFileTreeSelect = node.data
        getTreeDataList(params).then((data) => {
          if (data.result === true) {
            // 将新获取的数据合并到当前节点的children中
            node.childNodes = [...node.childNodes, ...data.resultdata.data];
            // 返回updatedChildren用于更新节点的children字段
            const updatedChildren = node.childNodes.map((child) => {
              child.checked =
                this.checkable &&
                this.checkedNodes.some((node) => node.id === child.id);
              return child;
            });
            resolve(updatedChildren);
            // this.getFileDataList(this.curFileTreeSelect.id);
          }
          else {
            this.$message({
              type: `warning`,
              message: `获取信息出错`,
            });
          }
        });
      }, 500);
    },
    handleNodeClick(data, b, c) {
      this.curFileTreeSelect = data
      this.getFileDataList(data.id);
    },
    openDrawer() {
      this.$refs.diretorySelect.open()
    },
    handleCurrentChange({ currentPage, pageSize }) {
      //选择跳转多少页
      this.page.currentPage = currentPage;
      this.page.pageSize = pageSize;
      let fdid = undefined
      if(this.curFileTreeSelect) {
        fdid = this.curFileTreeSelect.id
      }
      this.getFileDataList(fdid);
    },
    getTagDataList() {// el-tag的标签渲染
      return new Promise((resolve, reject) => {
        const params = {
        data: {
          fileBusinessTypeId: this.fileBusinessTypeId,
        },
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
      };
      getList(params).then((data) => {
        if (data.result) {
          const items = [];
          data.resultdata.data.forEach(function (obj, index) {
            items.push({
              label: obj.labelName,
              index: index,
              tagEffect: `plain`,
            });
          });

          this.items = items;
          console.log(this.items,"items");
        }
        resolve();
      });
      }).catch(()=>{
        reject
      })
    },
    changeColor(id) { // el-tag的点击事件
      // 点击改变主题
      const baginState = this.items[id].tagEffect == `plain`;
      this.items[id].tagEffect =
        this.items[id].tagEffect == `plain` ? `dark` : `plain`;
      this.searchkeys = [];
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].tagEffect == `dark`) {
          this.searchkeys.push(this.items[i].label);
        }
      }
      this.getFileDataList(this.selectedTab, this.searchkeys.join(`,`));
      // console.log(this.selectedTab,"this.selectedTab");
    },
    // 日期选择
    dataPickerChange() {
      this.queryForm.releaseTimeStart = this.fileReleaseUnitDate ? this.fileReleaseUnitDate[0] || "" : "";
      this.queryForm.releaseTimeEnd = this.fileReleaseUnitDate ? this.fileReleaseUnitDate[1] || "" : "";
    },
    // tab点击
    handleClick(tab, event) {
      this.curFileTreeSelect = undefined
      this.getTreeData();
    },
    //下载
    docDown(row) {
      const param = {
        data: {
          fileId: row.fileId,
          fileName: row.fileTitle,
          filePath: row.fileUrl,
        },
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
      };
      DOWN_FILES(`${webapp.knowledgeUrl}/fileBase/downLoadFile`, param);
    },
    reset() {
      //重置
      this.queryForm.searchKey = ``;
      this.queryForm.secrecyLevel = ``;
      this.queryForm.fileTitle = ``;
      this.queryForm.releaseUnit = ``;
      this.queryForm.releaseTimeStart = ``;
      this.queryForm.releaseTimeEnd = ``;
      this.fileReleaseUnitDate = null;
      this.queryForm.fileNumber = ``,
      this.queryForm.fileReleaseUnitName = ``;
      this.queryForm.downCountMin = null;
      this.queryForm.downCountMax = null;
      this.queryForm.fileContent = null;
      this.treedataId = `0001`;
      this.IsChecked = "";
      this.includesCheck = "";
      this.$set(this.queryForm, 'diretoryName', '');
      this.queryForm.diretoryId = ''
    },
    docPrew(item) {
      // console.log(docUrl,"docUrl");
      this.$refs.docPreviewPage.init(item);
    },
    docText(id) {
      this.$refs.docShowTextPage.init(id);
    },
  },
};
</script>

<style scoped lang="scss">
* {
  scrollbar-width: thin;
  scrollbar-color: #333 transparentize;
}

/*.left_m{
    height:;
  }*/
.search_d {
  margin: 20px;
  font-size: 16px !important;
}

.el-tag--small {
  height: 20px;
  padding: 0 5px;
  line-height: 19px;
  margin: 3px;
}

.search_t {
  margin-bottom: 5px;
  font-size: 16px;
}

.search_b {
  margin-top: 60px;
  margin-bottom: 20px;
  margin-left: 30%;
}

.doc-l {
  width: 100%;
  overflow-y: scroll;
}

.doc-i {
  background-color: white;
  width: 100%;
  height: auto;
  padding: 20px 20px 0 20px;
  margin-bottom: 10px;
}

.doc-i:last-child {
  margin-bottom: 0px;
}

.doc-it {
  margin-bottom: 10px;
}

.doc-it-co {
  padding: 10px;
  border: solid 1px #0e9aef;
  border-radius: 10px;
  float: left;
  margin-right: 30px;
  width: 150px;
  text-align: center;
}

.doc-it-tit {
  font-size: 0.938vw;
  font-weight: 700;
  margin-bottom: 0.26vw;
}

.doc-it-tab span {
  font-size: 14px;
  border-left: solid 1px #999999;
  padding: 0 10px;
}

.doc-it-tab span:first-child {
  border-left: none;
  padding-left: 0;
}

.doc-it-bth {
  float: right;
  margin-right: 50px;
  margin-top: -5px;
}

.doc-ib {
  width: 100%;
  padding: 5px 10px;
}

.doc-ib p {
  font-size: 14px;
  color: #999999;
}

.el-tag {
  height: 28px;
  line-height: 28px;
  padding: 0 10px;
}
</style>
<style scoped>
.search_cascader .el-checkbox__inner {
  border: 2px solid #999 !important;
}

.search-empty-list {
  color: #999;
  text-align: center;
  margin-top:300px;
}

/* .el-row--flex {
  padding: 10px;
} */
/deep/.is-leaf.el-tree-node_expand-icon {
  display: none;
}

.el-tree {
  min-width: 100%;
  height: calc(100% - 150px);
  display: inline-block;
}

.tree {
  overflow: auto;
  height: 680px;
  min-width: 100%;
}

.demo-drawer__footer .el-button {
  width: 270px;
  height: 35px;
  margin-left: 5px;
  margin-bottom: 10px;
}
</style>
